<?php

namespace app\common\model\mycurrency;

use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Control;
use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

class Device extends Model
{

    //use SoftDelete;

    // 表名
    protected $name = 'mycurrency_device';

    const STATUS_ZHENGCHENG = 1;//状态 = 正常
    const STATUS_JINYONG = 2;//状态 = 禁用

    const USE_STATUS_KONGXIAN = 1;//使用状态:1=空闲
    const USE_STATUS_SHIYONGZHONG = 2;//使用状态:2=使用中

    const IS_FAULT_WU = 1;//是否有故障 = 无;
    const IS_FAULT_YOU = 2;//是否有故障 = 有;

    const IS_ONLINE_BUZAIXIAN = 1;//是否在线 = 不在线
    const IS_ONLINE_ZAIXIAN = 2;//是否在线 = 在线

    const IS_INFRA_RED_YOU = 1;//是否有红外:1=有
    const IS_INFRA_RED_WU = 2;//是否有红外:2=无

    //生成设备唯一编号
    public static function getNumger(){
        $number = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('number', $number)->value('id');
        if (!$exists) {
            return $number;
        }
        return self::getNumger();
    }


    /**
     * 验证设备是否可以租赁
     * @param int $device_id 设备id
     * @param int $device_number 设备编号
    */
    public static function canorcantLease($device_id = null,$device_number = null){
        $where = [
            'deletetime' => null,
        ];
        if($device_id){
            $where['id'] = $device_id;
        }elseif ($device_number){
            $where['number'] = $device_number;
        }else{
            throw new Exception('查询参数错误');
            return false;
        }
        $device = self::where($where)->find();
        if (!$device){
            throw new Exception('设备不存在');
            return false;
        }
        if($device['status'] == self::STATUS_JINYONG){
            throw new Exception('设备不可用');
            return false;
        }
        //if($device['use_status'] == self::USE_STATUS_SHIYONGZHONG){
        //    throw new Exception('设备使用中');
        //    return false;
        //}
        if($device['is_fault'] == self::IS_FAULT_YOU){
            throw new Exception('设备存在故障');
            return false;
        }
        if($device['is_online'] == self::IS_ONLINE_BUZAIXIAN){
            throw new Exception('设备离线');
            return false;
        }
        return $device;
    }

    /**
     * 配置设备网络
     * @param int $code 指令
     * @param int $device_id 设备id
     * @param array $params 网络数据
     */
    public static function network($code,$device_id,$params){
        trace('========================配置网络==============================');
        $str_md5 = md5($params['ip'] . $params['port'] . $params['number'] . $params['password'] . $params['theme']);
        $str = '';
        $str .= $params['ip'];
        $str .= ",{$params['port']}";
        $str .= ",{$params['number']}";
        $str .= ",{$params['password']}";
        $str .= ",{$str_md5}";
        Log::info([$code,$params,$str]);
        Control::sending($device_id,(int)$code,$str,[]);
    }

    /**
     * 设备操作方法
     * @param int $code 指令码 (Analysis::CODE_KAIMEN等)
     * @param int $lattice_id 格口ID
     * @param array $params 附加参数，如开关灯时的模式和延时
     * @return bool|array 操作结果
     * @throws Exception 操作失败时抛出异常
     */
    public static function operateDevice($code, $lattice_id, $params = [])
    {
        // 1. 验证指令码是否有效
        $codeAll = [
            Analysis::CODE_KAIMEN,//开门
            Analysis::CODE_CHAXUNZHUANGTAI,//查询柜门状态
            //Analysis::CODE_KAIDENG,//开关灯
        ];
        if (!in_array($code, $codeAll)) {
            throw new Exception('指令类型错误');
        }
        
        // 2. 验证开关灯指令的附加参数
        if ($code == Analysis::CODE_KAIDENG) {
            if (!isset($params['pattern']) || !in_array($params['pattern'], ['0', '1', '2', 0, 1, 2])) {
                throw new Exception('灯光模式类型错误');
            }
            if (!isset($params['delayed']) || !is_numeric($params['delayed'])) {
                throw new Exception('延时时长不能为空或格式错误');
            }
        }
        
        // 3. 查询格口信息
        $lattice = DeviceLattice::where(['id' => $lattice_id, 'deletetime' => null])->find();
        if (!$lattice) {
            throw new Exception('柜门不存在');
        }
        
        // 4. 构建指令数据
        $data = '';
        if ($code == Analysis::CODE_KAIMEN) {
            $data = "49,{$lattice['number']}&1";
        } elseif ($code == Analysis::CODE_CHAXUNZHUANGTAI) {
            $data = "{$lattice['number']}";
        } elseif ($code == Analysis::CODE_KAIDENG) {
            $data = "{$lattice['number']}&{$params['pattern']}&{$params['delayed']}";
        }
        
        // 5. 构建指令扩展信息
        $instruction_extend = [
            'device_lattice_id' => $lattice->id,
        ];
        if ($code == Analysis::CODE_CHAXUNZHUANGTAI) {
            $instruction_extend['control_type'] = DeviceInstruction::CONTROL_TYPE_GUIMENKAIGUANZHUANGTAI;
        }
        
        // 6. 发送指令
        Control::sending($lattice->device_id, (int)$code, $data, $instruction_extend);
        
        return true;
    }

    public function store(){
        return $this->hasOne(MerchantStore::class, 'id', 'store_id');
    }


}
